<?php if (!defined('FIT_PATH')) exit('No direct script access allowed');
/**
 * @copyright 2009 - 2011 Bincent.com. All Rights Reserved.
 * @license http://www.apache.org/licenses/LICENSE-2.0
 * @package	FitPHP
 * @subpackage library
 * 
 * @author Hongbin Hsu <hongbin.hsu@gmail.com> Initial.
 * @version $Id: library/encrypt.php 1.0 2010-09-18 16:52 hongbin.hsu $
 */
 
// ------------------------------------------------------------------------

class Library_Encrypt
{
	private $encrypt = null;

	//----------------------------------------------------------
	/**
	 * 加密数据
	 *
	 * @param string $txt
	 * @param string $key
	 * @return string
	 */
	public function encode($txt, $key = ''){
	    srand((double)microtime() * 1000000); 
	    $encrypt = md5(rand(0, 32000)); 
	    $ctr = 0; 
	    $tmp = '';
	    $j = strlen($txt);
	    for($i = 0;$i < $j; $i++) { 
	        $ctr = $ctr == strlen($encrypt) ? 0 : $ctr; 
	        $tmp .= $encrypt[$ctr].($txt[$i] ^ $encrypt[$ctr++]); 
	    } 
	    return base64_encode($this->merge($tmp, $key));
	} 
	
	//----------------------------------------------------------
	/**
	 * 解密数据
	 *
	 * @param string $txt
	 * @param string $key
	 * @return string
	 */
	public function decode($txt, $key = ''){
	    $txt = $this->merge(base64_decode($txt), $key); 
	    $tmp = '';
	    $j = strlen($txt);
	    for ($i = 0;$i < $j; $i++){ 
	        $md5 = $txt[$i];
	        $tmp .= $txt[++$i] ^ $md5;
	    } 
	    return $tmp; 
	} 
	
	//----------------------------------------------------------
	/**
	 * 数据合并
	 *
	 * @param string $txt
	 * @param string $encrypt
	 * @return string
	 */
	private function merge($txt, $encrypt){ 
	    $encrypt = md5($encrypt); 
	    $ctr = 0; 
	    $tmp = ''; 
	    for($i = 0; $i < strlen($txt); $i++) { 
	        $ctr = $ctr == strlen($encrypt) ? 0 : $ctr; 
	        $tmp .= $txt[$i] ^ $encrypt[$ctr++]; 
	    } 
	    return $tmp; 
	}
}